//
//  ViewController.m
//  BTDemo
//
//  Created by Avery on 14-8-20.
//  Copyright (c) 2014年 Alvin. All rights reserved.
//

#import "ViewController.h"
#import "BTManager.h"
#import "LMContainsLMComboxScrollView.h"
#import "UITextView+EditableTextView.h"
#import "BTSendData.h"
#import "DataUtil.h"

#define kDropDownListTag 1000

@interface ViewController ()
{
    LMContainsLMComboxScrollView *bgScrollView;
    LMComBoxView *comBox;
}
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupComBoxView];
}

- (void)setupComBoxView
{
    bgScrollView = [[LMContainsLMComboxScrollView alloc]initWithFrame:CGRectMake(110, 727, 480 , 500)];
    bgScrollView.backgroundColor = [UIColor clearColor];
    bgScrollView.showsVerticalScrollIndicator = NO;
    bgScrollView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:bgScrollView];
 
    comBox = [[LMComBoxView alloc]initWithFrame:CGRectMake(0, 0, 450, 60)];
    comBox.backgroundColor = [UIColor whiteColor];
    comBox.arrowImgName = @"down_dark0.png";
    NSMutableArray *itemsArray = [NSMutableArray arrayWithObjects:@"SetTime",@"ChooseClub",@"Get ANA State",@"Start Bearing", nil];
    comBox.titlesList = itemsArray;
    comBox.delegate = self;
    comBox.supView = bgScrollView;
    [comBox defaultSettings];
    comBox.tag = kDropDownListTag + 1;
    [bgScrollView addSubview:comBox];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)startMonitorBTStatus
{
    [[BTManager shareInstance]setCompletion_status:^(BTStatus status){
        switch (status) {
            case BTStatusConnected:
                NSLog(@"连接已建立！");
                _infoTextView.text = [NSString stringWithFormat:@"%@\n Connected",_infoTextView.text];
                break;
            case BTStatusDisconnect:
                NSLog(@"连接已断开！");
                _infoTextView.text = [NSString stringWithFormat:@"%@\n Disconnected",_infoTextView.text];
                break;
                
            default:
                break;
        }
    }];
}
- (IBAction)onClickConnect:(id)sender {
    [self startMonitorBTStatus];
    [[BTManager shareInstance]connectToDevice];
    
    BOOL isConnected = [[BTManager shareInstance]isDeviceConnected];
    if (isConnected) {
        [_infoTextView appendTextData:@"Device Connected!"];
        NSLog(@"Connected！");
    }else{
        [_infoTextView appendTextData:@"No connected device found!"];
        NSLog(@"Disconnected！");
    }
    

}
- (IBAction)onClickDisConnect:(id)sender {
//    if([[BTDriver defaultDriver] isBluetoothConnected]){
//        NSLog(@"IS connected!");
//        [[BTDriver defaultDriver] destroyEnvironment];
//    }
}
- (IBAction)onClickSend:(id)sender {
    NSString * currentSelected = comBox.getTitleContent;
    
    if (!currentSelected || [currentSelected isEqualToString:@""]) {
        [_infoTextView appendTextData:@"Please choose command!"];
        return;
    }
    NSData *cmdData = [self generateCommand:currentSelected];
    
    [_infoTextView appendTextData:[NSString stringWithFormat:@"-> Choose %@",currentSelected]];
    [_infoTextView appendTextData:[NSString stringWithFormat:@"-> Command is %@",cmdData]];
    
    BTSendData *sendData = [[BTSendData alloc] initWithCmdData:cmdData];
//    sendData.responseModel = ;
    
    [sendData setVerifyCallBack:^(NSData *data)
     {
         return BTSendDataCallBackFinish;
     }];
    
    [sendData setResponseCallBack:^(NSError *error, NSData *model)
     {
         if(error)
         {
             NSLog(@"Get error:!!%@",error);
             return;
         }
         NSLog(@"Get response:%@",model);
         [_infoTextView appendTextData:[NSString stringWithFormat:@"Get response:%@",model]];
     }];
    
    [[BTManager shareInstance] sendData:sendData];
    
}

- (NSData *)generateCommand:(NSString *)str{
    if ([str isEqualToString:@"SetTime"]) {
        time_t              seconds;
        struct tm       *   pTm;
        
        time(&seconds);
        
        //Calculate time
        pTm = localtime(&seconds);                                  /* Convert to tm structure */
        seconds =   pTm->tm_sec   +
        pTm->tm_min             *   60          +
        pTm->tm_hour            *   3600        +
        pTm->tm_yday            *   86400       +
        (pTm->tm_year-70)       *   31536000    +
        ((pTm->tm_year-69)/4)   *   86400       -
        ((pTm->tm_year-1)/100)  *   86400       +
        ((pTm->tm_year+299)/400)*   86400;
        
        CMD_SETTIME_T  cmd = {0};
        cmd.Command = CMD_SET_TIME;
        cmd.Seconds = seconds;
        cmd.Checksum = CalcChecksum(&cmd, sizeof(CMD_SETTIME_T));
        
        NSData *data = [NSData dataWithBytes:((void*)&cmd) length:sizeof(CMD_SETTIME_T)];
        return data;
    }
    else if ([str isEqualToString:@"ChooseClub"]) {
        /* 设置杆信息 */
        CMD_CLUB_SPEC_T   cmd = {0};      // Command buffer
        
        cmd.Command       = CMD_SET_CLUB;                       // Set club spec command
        cmd.ShaftLength   = 111.76f;
        cmd.LieAngle      = 50.00f*DEG_2_RAD;
        cmd.LoftAngle     = 10.50f*DEG_2_RAD;
        cmd.TorqueAngle   = 4.1f*DEG_2_RAD;
        cmd.HeadMass      = 200.0;
        strncpy(cmd.Model, "CallowayX10", sizeof(cmd.Model));
        strncpy(cmd.Type, "MensSteel", sizeof(cmd.Type));
        strncpy(cmd.Key, "d1", sizeof(cmd.Key));
        strncpy(cmd.Name, "Driver", sizeof(cmd.Name));
        
        
        cmd.Checksum = CalcChecksum(&cmd, sizeof(CMD_CLUB_SPEC_T));
        
        NSData *data = [NSData dataWithBytes:((void*)&cmd) length:sizeof(CMD_CLUB_SPEC_T)];
        return data;

    }
    else if ([str isEqualToString:@"Get ANA State"]) {
        unsigned char  cmd = CMD_GET_ANA_STATE;                // Get the club Matrix
        NSData *data = [NSData dataWithBytes:((void*)&cmd) length:sizeof(unsigned char)];
        return data;
    }
    else if ([str isEqualToString:@"Start Bearing"]) {
        /* 设置杆校准信息 */
        ANA_PARAMS_T params = {0};
        params.PitchAng = 0.0;                        // Want shaft horizontal
        params.PitchTol = 10 * DEG_2_RAD;           // Tolerance +/- 10 degrees
        params.BearingStab = 1000;           // Hold steady for 1 second
        params.Flags.UseIndicators = true;     // Want iTrainer LED indication
        
        FloatMatrix3x3_T Matrix = {1,0,0, 0,1,0, 0,0,1};
        
        CMD_SET_ANA_T  pCmd={0};     // Cast a pointer over the CMD buffer
        
        memset(&pCmd,0, sizeof(CMD_SET_ANA_T));   // Zap the command buffer too
        pCmd.Command   = CMD_SET_ANA_MODE;                         // Command set
        pCmd.Mode      = ANA_MODE_BEARING;                         // Set the Mode we want
        
        memcpy(&pCmd.Params,&params,sizeof(ANA_PARAMS_T));       // Copy params across
        
        memcpy(&pCmd.Matrix,&Matrix,sizeof(FloatMatrix3x3_T)); // Copy starting matrix over
        
        pCmd.Checksum  = CalcChecksum(&pCmd, sizeof(CMD_SET_ANA_T));// Requires a checksum
        
        NSData *data = [NSData dataWithBytes:((void*)&pCmd) length:sizeof(CMD_SET_ANA_T)];
        return data;
        
    }
    else{
        return nil;
    }
}

#pragma mark -LMComBoxViewDelegate
-(void)selectAtIndex:(int)index inCombox:(LMComBoxView *)_combox
{
    NSLog(@"Current selected is:%d",index);
}
@end
